package com.qf.electronic.mall.login.web.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.qf.constant.CookieConstant;
import com.qf.constant.RabbitConstant;
import com.qf.constant.RedisConstant;
import com.qf.constant.ResultBeanConstant;
import com.qf.dto.ResultBean;
import com.qf.entity.TUser;
import com.qf.login.api.ILoginService;
import com.qf.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisAccessor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("login")
@CrossOrigin(origins = "*",maxAge = 3600,allowCredentials = "true")
public class LoginController {
    @Reference
    private ILoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("loginUI")
    public String loginUI(){
        return "login";
    }

    //登录
    @RequestMapping("checkLogin")
    public String checkLogin(String uname, String password, HttpServletResponse response){
        //验证用户名和密码是否正确
        ResultBean resultBean=loginService.checkLogin(uname,password);
        int i = (int)resultBean.get(ResultBeanConstant.CODE);
        if(i==0){
            //登录成功
            String uuid = UUID.randomUUID().toString();
            //往redis里存组织键user:login:uuid
            String redisKey = StringUtil.getRedisKey(RedisConstant.USER_LOGIN, uuid);
            redisTemplate.opsForValue().set(redisKey,resultBean.get(ResultBeanConstant.DATA),30, TimeUnit.DAYS);

            //把uuid存到Cookie中
            Cookie cookie = new Cookie(CookieConstant.USER_LOGIN, uuid);
            cookie.setMaxAge(30*24*60*60);
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            return null;
        }

        return "redirect:showLogin";
    }


    //判断用户是否已经登录
    @RequestMapping("checkIsLogin")
    @ResponseBody
    public ResultBean checkIsLogin(@CookieValue(name = CookieConstant.USER_LOGIN,required = false)String uuid){
        return loginService.checkIsLogin(uuid);
    }
}
